package org.looop.chuck.http;

import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.looop.chuck.parser.HTMLParser;
import org.looop.chuck.parser.HTMLParserFactory;
import org.looop.chuck.persistence.PersistenceManager;
import org.looop.chuck.task.TaskFailedReason;
import org.looop.chuck.task.URLTaskManager;

public class RequestHandler implements Runnable {
	private HttpClient httpClient;
	private String url;
	private URLTaskManager taskManager;
	private PersistenceManager persistenceManager;
	private HTMLParserFactory htmlParserFactory;
	

	public RequestHandler(HttpClient httpClient, String url,
			URLTaskManager taskManager, PersistenceManager persistenceManager,HTMLParserFactory htmlParserFactory) {
		super();
		this.httpClient = httpClient;
		this.url = url;
		this.taskManager = taskManager;
		this.persistenceManager = persistenceManager;
		this.htmlParserFactory = htmlParserFactory;
	}

	@Override
	public void run() {
		HttpMethod method = new HttpGetMethod(url);
		method.getParams().setHttpElementCharset("utf-8");
		method.getParams().setContentCharset("utf-8");
		try {
			int responseCode = httpClient.executeMethod(method);
			InputStream is = method.getResponseBodyAsStream();
			if(is == null){
				System.out.println("is == null");
				failed(url + " response code is not 200");
				return;
			}
			HTMLParser parser = htmlParserFactory.createHTMLParser(url, persistenceManager, taskManager);
			Boolean isSuccess = parser.parseDOM(is);
			if(isSuccess){
				success();
			}else{
				failed("parse DOM failed");
			}
			
		} catch (Exception e) {
			failed(e);
			return;
		}finally{
			method.releaseConnection();
		}
		
	}
	
	private void failed(Exception e) {
		taskManager.failedTask(url, new TaskFailedReason(e, null));
	}

	private void failed(String reason){
		taskManager.failedTask(url, new TaskFailedReason(null, reason));
	}
	
	
	private void success(){
		taskManager.successTask(url);
	}

}
